package com.hyc.cloud.mylb.impl;

import com.hyc.cloud.mylb.MyLoadBalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 手写轮询算法.
 *
 * @className: MyLoadBalancerImpl
 * @author: hyc
 * @date: 2022-01-14 14:46
 */
@Component
public class MyLoadBalancerImpl implements MyLoadBalancer {

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    @Override
    public ServiceInstance getServiceInstance(List<ServiceInstance> serviceInstances) {
        if (serviceInstances == null || serviceInstances.size() < 1) {
            return null;
        }
        int index = incrementAndGet() % serviceInstances.size();

        return serviceInstances.get(index);
    }

    private int incrementAndGet() {
        int current;

        int next;

        do {
            current = this.atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        } while (!this.atomicInteger.compareAndSet(current, next));

        return next;
    }
}